package con.shake;

import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
import android.widget.Button;

public class ShakeAppActivity extends PreferenceActivity {
    /** Called when the activity is first created. */
	private boolean isServiceRunning;
	private static final String ENABLE = "ENABLE";
	private static final String DISABLE = "DISABLE";
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	try {
    		 super.onCreate(savedInstanceState);
    		 addPreferencesFromResource(R.xml.preferences);
    		 
    	     setContentView(R.layout.main);
    	     final Button startStopServiceButton = (Button)findViewById(R.id.start_stop_service);
    	     isServiceRunning =  isServiceRunning(this, MyService.class);
    	     if(isServiceRunning){
    	    	 startStopServiceButton.setText(DISABLE);
    	     }else{
    	    	 startStopServiceButton.setText(ENABLE);
    	     }
    	     startStopServiceButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(ENABLE.equals(((Button)v).getText())){
						startService(new Intent(ShakeAppActivity.this, MyService.class));
						startStopServiceButton.setText(DISABLE);
					}else{
						stopService(new Intent(ShakeAppActivity.this, MyService.class));
						startStopServiceButton.setText(ENABLE);
					}					
				}
			});
    	     
    	     
    	     
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    public static boolean isServiceRunning(Context context,Class serviceClassName){
    	
        final ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        for (RunningServiceInfo runningServiceInfo : services) {
            if (runningServiceInfo.service.getClassName().equals(serviceClassName.getCanonicalName())){
                return true;
            }
        }
        return false;
     }

}